package com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bean.LoginBean;
import com.bean.LoginSuccessBean;
import com.constant.Constant;
import com.constant.PackageType;
import com.event.DisconnectEvent;
import com.google.gson.Gson;
import com.interfaces.IEvent;
import com.interfaces.IEventListener;
import com.interfaces.IShortSocket;
import com.lottery.R;
import com.util.CheckAvailUtil;
import com.util.DataTypeUtil;
import com.util.DialogIos;
import com.util.JsonUtils;
import com.util.LogUtil;
import com.util.MD5Utils;
import com.util.NetworkUtil;
import com.util.SocketTask;
import com.util.ToastUtils;
import com.util.Utils;

import java.util.concurrent.Executors;

/**
 * Created by Mars on 2017/9/20.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener, IEventListener {

    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.length() > 0) {
                mDelete.setVisibility(View.VISIBLE);
            } else {
                mDelete.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };
    private ImageView mDelete;
    private EditText mEtPhone;
    private View mContainer;
    private EditText mEtPsw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initUI();
        setOnclick();

    }

    private void setOnclick() {
        findViewById(R.id.btnLogin).setOnClickListener(this);
        findViewById(R.id.btnRegister).setOnClickListener(this);
        findViewById(R.id.TextForgetPsw).setOnClickListener(this);
    }

    private void initUI() {

        mContainer = findViewById(R.id.container);
        mContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mContainer.setFocusable(true);
                mContainer.setFocusableInTouchMode(true);
                mContainer.requestFocus();
                Utils.KeyBoardCancel(LoginActivity.this);
                return false;
            }
        });

        TextView tvVersion = findViewById(R.id.tv_Version);
        tvVersion.setText(Utils.getVersionName().toString());

        mDelete = findViewById(R.id.img_delete);
        mDelete.setOnClickListener(this);

        mEtPhone = findViewById(R.id.et_Phone);
        mEtPhone.addTextChangedListener(mTextWatcher);

        mEtPsw = findViewById(R.id.et_Psw);
    }


    @Override
    public boolean onEvent(IEvent iEvent) {

        if (iEvent instanceof DisconnectEvent){
            ToastUtils.showToast("DisconnectEvent");
        }

        if (iEvent instanceof LoginSuccessBean) {
            LoginSuccessBean event = (LoginSuccessBean) iEvent;
            String code = event.getCode();
            LogUtil.e("code = " + code);
        }
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_delete:
                mEtPhone.setText("");
                break;
            case R.id.container:
                Utils.KeyBoardCancel(this);
                mContainer.setFocusable(true);
                mContainer.setFocusableInTouchMode(true);
                mContainer.requestFocus();
                break;
            case R.id.btnLogin:
                login();
                break;
            case R.id.btnRegister:
                register();
                break;
            case R.id.TextForgetPsw:
                forgotPsw();
                break;
        }
    }

    private void forgotPsw() {
        startActivity(new Intent(this, ForgetPswActivity.class));
    }

    private void register() {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    private void login() {
        if (!NetworkUtil.isNetworkAvailable()) {
            ToastUtils.showToast(R.string.network_unable);
            return;
        }
        String mPhone = mEtPhone.getText().toString();
        String mPsw = mEtPsw.getText().toString();
        if (TextUtils.isEmpty(mPhone)) {
            DialogIos.tan(this, getResources().getString(R.string.please_fill_phone), mEtPhone);
            return;
        }
        if (!CheckAvailUtil.mobileNum(mPhone)) {
            DialogIos.tan(this, getResources().getString(R.string.please_fill_msg), mEtPhone);
            return;
        }
        if (TextUtils.isEmpty(mPsw)) {
            DialogIos.tan(this, getResources().getString(R.string.psw_not_null), mEtPsw);
            return;
        }
        LoginBean loginBean = new LoginBean(mPhone, MD5Utils.md5(mPsw));
        String sBody = new Gson().toJson(loginBean);
        String s = DataTypeUtil.encoder(sBody);
        // TODO: 2017/10/18 发送请求
//        Actions.getInstance().doLogin(s);
        LogUtil.e(sBody);
        SocketTask socketTask = new SocketTask(Constant.IP, Constant.PORT, PackageType.USER_LOGIN,
                (short) 0, s, shortListener);
        socketTask.executeOnExecutor(Executors.newCachedThreadPool(), "");
    }

    private IShortSocket shortListener = new IShortSocket() {
        @Override
        public void getData(String json) {
            LogUtil.e("json = " + json);
            if (!TextUtils.isEmpty(json)) {
                LoginSuccessBean result = JsonUtils.getResult(json, LoginSuccessBean.class);
                if (!result.getCode().equals("200")) {
                    DialogIos.tan(LoginActivity.this, result.getMsg(), mEtPsw);
                } else {
                    startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                    finish();
                }

            }
        }

        @Override
        public void getDataError() {

        }

        @Override
        public void connectError() {

        }
    };

}
